import { useState, useRef, useEffect } from 'react';
import { motion } from 'framer-motion';
import BottomNav from '../components/BottomNav';
import { PaperAirplaneIcon } from '@heroicons/react/24/outline';
import { AuthenticatedRequest } from '../api/authenticatedRequest';

// 定义消息类型
interface Message {
  id: string;
  content: string;
  sender: 'user' | 'ai';
  timestamp: Date;
}

export default function AIChatPage() {
  // 消息列表状态
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      content: '你好，有什么我可以帮助你的吗？',
      sender: 'ai',
      timestamp: new Date()
    }
  ]);
  
  // 输入框状态
  const [inputValue, setInputValue] = useState('');
  
  // 加载状态
  const [isLoading, setIsLoading] = useState(false);
  
  // 滚动到底部的引用
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const messagesContainerRef = useRef<HTMLDivElement>(null);

  // 滚动到底部的函数
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  // 当消息列表更新时，滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 发送消息函数
  const handleSendMessage = async () => {
    if (!inputValue.trim() || isLoading) return;

    // 创建用户消息对象
    const userMessage: Message = {
      id: `user-${Date.now()}`,
      content: inputValue.trim(),
      sender: 'user',
      timestamp: new Date()
    };

    // 添加用户消息到列表
    setMessages(prevMessages => [...prevMessages, userMessage]);
    
    // 清空输入框
    setInputValue('');
    
    try {
      // 设置加载状态
      setIsLoading(true);
      
      // 调用后端API
      const response = await AuthenticatedRequest.get<string>(
        '/api/ai/chat',
        { message: userMessage.content }
      );
      
      // 检查响应是否成功
      if (response.code === '200' && response.data) {
        // 创建AI回复消息对象
        const aiResponseMessage: Message = {
          id: `ai-${Date.now()}`,
          content: response.data,
          sender: 'ai',
          timestamp: new Date()
        };
        
        // 添加AI回复到列表
        setMessages(prevMessages => [...prevMessages, aiResponseMessage]);
      } else {
        // 创建错误回复消息
        const errorMessage: Message = {
          id: `ai-error-${Date.now()}`,
          content: response.msg || '抱歉，我暂时无法回答这个问题，请稍后再试。',
          sender: 'ai',
          timestamp: new Date()
        };
        
        // 添加错误回复到列表
        setMessages(prevMessages => [...prevMessages, errorMessage]);
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      
      // 创建错误回复消息
      const errorMessage: Message = {
        id: `ai-error-${Date.now()}`,
        content: '抱歉，连接服务器时出错，请稍后再试。',
        sender: 'ai',
        timestamp: new Date()
      };
      
      // 添加错误回复到列表
      setMessages(prevMessages => [...prevMessages, errorMessage]);
    } finally {
      // 重置加载状态
      setIsLoading(false);
    }
  };

  // 处理输入框回车事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  return (
    <div className="pb-16 flex flex-col h-screen max-w-md mx-auto bg-white dark:bg-gray-900">
      <motion.div 
        ref={messagesContainerRef}
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        className="p-4 flex-1 overflow-y-auto"
      >
        <h1 className="text-2xl font-bold mb-6 dark:text-white">AI助手</h1>
        
        <div className="space-y-4">
          {messages.map((message) => (
            <div 
              key={message.id} 
              className={`flex ${message.sender === 'user' ? 'justify-end' : 'justify-start'}`}
            >
              <motion.div
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                className={`max-w-[80%] p-3 rounded-xl ${message.sender === 'user' 
                  ? 'bg-primary text-white rounded-br-none' 
                  : 'bg-gray-100 dark:bg-gray-700 rounded-bl-none dark:text-white'}`}
              >
                <p>{message.content}</p>
              </motion.div>
            </div>
          ))}
          
          {/* 加载指示器 */}
          {isLoading && (
            <div className="flex justify-start">
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="max-w-[80%] p-3 bg-gray-100 dark:bg-gray-700 rounded-xl rounded-bl-none dark:text-white"
              >
                <div className="flex space-x-1">
                  <div className="w-2 h-2 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: '0ms' }}></div>
                  <div className="w-2 h-2 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: '150ms' }}></div>
                  <div className="w-2 h-2 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: '300ms' }}></div>
                </div>
              </motion.div>
            </div>
          )}
          
          {/* 用于滚动到底部的参考元素 */}
          <div ref={messagesEndRef} />
        </div>
      </motion.div>
      
      <div className="p-4 border-t border-gray-200 dark:border-gray-700">
        <div className="flex items-center bg-gray-100 dark:bg-gray-700 rounded-full px-4 py-2">
          <input 
            type="text" 
            placeholder="输入消息..."
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            disabled={isLoading}
            className="flex-1 bg-transparent outline-none text-sm dark:text-white"
          />
          <button 
            onClick={handleSendMessage}
            disabled={!inputValue.trim() || isLoading}
            className={`p-2 rounded-full ${!inputValue.trim() || isLoading ? 'bg-gray-400 cursor-not-allowed' : 'bg-primary text-white hover:bg-primary/90'}`}
          >
            <PaperAirplaneIcon className="w-5 h-5" />
          </button>
        </div>
      </div>
      
      <BottomNav />
    </div>
  );
}